
package com.probiz.estore.core.security;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.taglibs.authz.AuthorizeTag;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.core.util.ContextUtil;

/**
 * 授权菜单
 */
public class AuthorizeMenuTag extends AuthorizeTag {
	private static final long	serialVersionUID	= 7789389345552204238L;
	private static final Log 	logger    			= LogFactory.getLog(AuthorizeMenuTag.class);
	private String				doAction;	
	private String				resourceString;
	
	public String getDoAction() {
		return doAction;
	}

	public String getResourceString() {
		return resourceString;
	}

	public void setDoAction(String doAction) {
		this.doAction = doAction;
	}

	public void setResourceString(String resourceString) {
		this.resourceString = resourceString;
	}

	public int doStartTag() throws JspException {
	    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		String contextPath = request.getContextPath();
	    resourceString = resourceString.replace(contextPath, "");
		ConfigAttributeDefinition cad = null;
		if(!ConfigUtil.getInstance().getIsStoreFront()){
			UrlRegExpBasedFilterInvocationDefinitionMap source = (UrlRegExpBasedFilterInvocationDefinitionMap) ContextUtil.getSpringBeanById("urlRegExpBasedFilterInvocationDefinitionMap");
			cad = source.lookupAttributes4Menu(resourceString);
		}else{
			//TODO 前台
		}
		if (cad != null) {
			this.setIfAnyGranted(getRoleNames(cad));
			return super.doStartTag();
		}
		// if not found these resource .then include.
		return EVAL_BODY_INCLUDE;
	}
	
	private String getRoleNames(ConfigAttributeDefinition cad)
	{
	    StringBuffer roleNameSb = new StringBuffer();
        Iterator it = cad.getConfigAttributes();
        int count = 0;
        while (it.hasNext()) {
            ConfigAttribute ca = (ConfigAttribute) it.next();                
            // get the role name from configAttribute
            if (count == 0) {
                roleNameSb.append(ca.getAttribute());
            } else {
                roleNameSb.append("," + ca.getAttribute());
            }
            count++;
        }
        return roleNameSb.toString();
	}

}
